package com.sk.weichat.mvp.presenter;

import android.content.Context;

import com.sk.weichat.bean.User;
import com.sk.weichat.broadcast.CardcastUiUpdateUtil;
import com.sk.weichat.helper.FriendHelper;
import com.sk.weichat.mvp.contract.PersonalCenterContract;
import com.sk.weichat.ui.base.CoreManager;
import com.sk.weichat.util.ToastUtil;
import com.xuan.xuanhttplibrary.okhttp.HttpUtils;
import com.xuan.xuanhttplibrary.okhttp.callback.BaseCallback;
import com.xuan.xuanhttplibrary.okhttp.result.ObjectResult;
import com.xuan.xuanhttplibrary.okhttp.result.Result;

import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;

/**
 * 个人信息逻辑控制器
 */
public class PersonalCenterPresenter {

    private final Context mContext;
    private final CoreManager mCoreManager;
    private final PersonalCenterContract.BaseView mBaseView;

    public PersonalCenterPresenter( CoreManager coreManager, PersonalCenterContract.BaseView baseView){
        this.mBaseView = baseView;
        this.mContext = (Context) baseView;
        this.mCoreManager = coreManager;
    }

    /**
     * 获取自己的个人信息
     */
    public void getUserInfo(){
        mBaseView.onUpdateUI( mCoreManager.getSelf());
    }

    /**
     * 获取他人的个人信息
     * @param mUserId 他人的userId
     */
    public void getOtherUserInfo(String mUserId){
        Map<String, String> params = new HashMap<>();
        params.put("access_token", mCoreManager.getSelfStatus().accessToken);
        params.put("userId", mUserId);

        HttpUtils.get().url(mCoreManager.getConfig().USER_GET_URL)
                .params(params)
                .build()
                .execute(new BaseCallback<User>(User.class) {

                    @Override
                    public void onResponse(ObjectResult<User> result) {
                        if (Result.checkSuccess(mContext, result)) {
                            User user = result.getData();
                            if (user.getUserType() != 2) {// 公众号不做该操作 否则会将公众号的status变为好友
                                // 服务器的状态 与本地状态对比
                                if (FriendHelper.updateFriendRelationship(mCoreManager.getSelf().getUserId(), user)) {
                                    CardcastUiUpdateUtil.broadcastUpdateUi(mContext);
                                }
                            }
                            mBaseView.onUpdateUI(user);
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        ToastUtil.showNetError(mContext);
                    }
                });
    }

}
